package com.fyl.datasource.spring.boot.autoconfigure;

import com.fyl.datasource.aop.TargetDataSourceAnnotationAdvisor;
import com.fyl.datasource.aop.TargetDataSourceAnnotationMethodInterceptor;
import com.fyl.datasource.config.druid.DruidDataSourceConfiguration;
import com.fyl.datasource.creator.DataSourceCreator;
import com.fyl.datasource.creator.DynamicDataSourceCreator;
import com.fyl.datasource.provider.DataSourceProvider;
import com.fyl.datasource.provider.DynamicDataSourceProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.*;

import javax.sql.DataSource;

@Configuration
@EnableConfigurationProperties(DynamicDataSourceProperties.class)
@AutoConfigureBefore({DataSourceAutoConfiguration.class})
@Import(DruidDataSourceConfiguration.class)
@ConditionalOnProperty(prefix = DynamicDataSourceProperties.PREFIX, name = "enabled", havingValue = "true", matchIfMissing = true)
public class DynamicDataSourceAutoConfiguration {

    @Autowired
    private DynamicDataSourceProperties properties;


    @Bean
    @ConditionalOnMissingBean
    public DataSourceCreator dynamicDataSourceCreator() {
        DynamicDataSourceCreator dynamicDataSourceCreator = new DynamicDataSourceCreator();
        dynamicDataSourceCreator.setDruidGlobalConfig(properties.getDruid());
        dynamicDataSourceCreator.setHikariGlobalConfig(properties.getHikari());
        return dynamicDataSourceCreator;
    }

    @Bean
    @ConditionalOnMissingBean
    public DataSourceProvider dynamicDataSourceProvider() {
        return new DynamicDataSourceProvider(properties);
    }


    @Bean
    @ConditionalOnMissingBean
    public DataSource dataSource(DataSourceProvider dataSourceProvider) {
        DynamicDataSource dataSource = new DynamicDataSource();
        dataSource.setPrimary(properties.getPrimary());
        dataSource.setProvider(dataSourceProvider);
        return dataSource;
    }

    @Bean
    @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
    @ConditionalOnMissingBean
    public TargetDataSourceAnnotationAdvisor targetDataSourceAnnotationAdvisor() {
        TargetDataSourceAnnotationMethodInterceptor methodInterceptor = new TargetDataSourceAnnotationMethodInterceptor();
        TargetDataSourceAnnotationAdvisor advisor = new TargetDataSourceAnnotationAdvisor(methodInterceptor);
//        advisor.setOrder(properties.geOrder());
        return advisor;
    }

}
